import datetime

from fastapi import FastAPI, Depends
from fastapi.responses import StreamingResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm

from models import User
from serializer import ChatForm, PasswordReset
from utils.server import event_generator_ollama, get_db, get_current_user
from utils.user import reset_user_password, authenticate_user, create_access_token
from config import ACCESS_TOKEN_EXPIRE_MINUTES


app = FastAPI()
# 配置CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许的源列表
    allow_credentials=True,  # 是否允许发送凭据（如cookies）
    allow_methods=["*"],  # 允许所有HTTP方法
    allow_headers=["*"],  # 允许所有请求头
)
        # yield f"data: {res['message']['content']}\n"

@app.post("/create_user")
async def create_user(form_data: OAuth2PasswordRequestForm = Depends(), db=Depends(get_db)):
    username = form_data.username
    password = form_data.username
    client_secret = form_data.client_secret
    if client_secret == "yfkj@2025":
        try:
            user = User(username=username, password=password)
            db.save(user)
        except:
            print("保存失败")
    return JSONResponse(content={ "msg":"创建成功"})


@app.post("/reset_passwd")
async def reset_passwd(
    reset_data: PasswordReset,
    db = Depends(get_db)
):
    """
    重置用户密码的端点
    只有已认证的用户可以重置自己的密码
    """
    if reset_data.secret != "yfkj@2025":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="请输入管理员密钥！"
        )
    
    user = reset_user_password(db, reset_data.username, reset_data.new_password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found"
        )
    return {"message": "Password has been reset successfully"}


@app.post("/get_token")
async def get_token(form_data: OAuth2PasswordRequestForm = Depends(), db=Depends(get_db)):
    user = authenticate_user(db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect credentials")
    
    access_token_expires = datetime.timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token({"sub": user.username}, expires_delta=access_token_expires)
    return {"access_token": access_token, "token_type": "bearer"}


@app.post("/chat_r1")
async def chat_r1(
    chat_form: ChatForm=Depends(),
    current_user: User = Depends(get_current_user)
):
    """
    聊天端点，需要用户登录
    """
    return StreamingResponse(
        event_generator_ollama(chat_form.message), 
        media_type="text/event-stream"
    )


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
